from __future__ import print_function

## Import list
from cli import CLI
import logging
from tempfile import mkstemp
from subprocess import Popen
#from os.path import expanduser, getsize, abspath, exists, dirname, isdir, basename
from os import getcwd, makedirs, remove, walk, stat, link, symlink, unlink, system, urandom, close
import string
#import ConfigParser
import utils
from shutil import copy2
from base64 import b32encode

class Image(CLI):
    def makeThumbs(self):
        thumbSizes = {
                    1: "1024x768",
                    2: "500x275",
                    3: "240x180",
                    4: "100x75"}
        for media in self._db.imagesMissingThumbs():
            try:
                for ndx in thumbSizes:
                    thumbsize = thumbSizes[ndx]
                    fqpn = utils.getFqpnFromMediaObject(self._pdriveFiles, media)
                    print("Converting {}: ".format(fqpn), end='')
                    tempObj = mkstemp(suffix=".png", dir="/dev/shm")
                    tempFD = tempObj[0]
                    temp = tempObj[1]
                    #convert -thumbnail 500x275 -background none  -gravity center -extent 500x275 origin.jpeg target.png
                    Popen(['/usr/bin/convert', '-thumbnail', thumbsize, '-background', 'none', '-gravity', 'center', '-extent', thumbsize, fqpn, temp], close_fds=True).wait()
                    sha256Hash = utils.sha256HashFile(temp)
                    fileStats = stat(temp)
                    if (fileStats.st_size < 1):
                        print("Convert failed")
                        break
                    mime = utils.fileMime(temp)
                    mediaType = string.split(mime, "/")[0]
                    fileType = string.split(mime, "/")[1]
                    fileDestFqpn = utils.getFqpnFromData(self._pdriveFiles, fileStats.st_size, sha256Hash, fileType)
                    copy2(temp, fileDestFqpn)
                    unlink (temp)
                    close(tempFD)
                    self._db.newImageThumbnail(media["sha256Hash"], sha256Hash, fileStats.st_size, ndx)
                    print(" {}:{} done".format(fileDestFqpn, ndx))
            except:
                raise

    def rmThumbs(self):
        for media in self._db.getAllThumbnails():
            try:
                unlink(utils.getFqpnFromData(self._pdriveFiles, media["filesize"], media["sha256Hash"], media["fileType"]))
                self._db.rmTumbnail(media["sha256Hash"])
            except:
                raise
            
            
